import { CMenu, menuItem } from 'stores/model';
import { Router } from 'vue-router';


export function buildMenuTree () {
  //懒加载组件
  const loadView = (viewPath: string | null) => {
    // 用字符串模板实现动态 import 从而实现路由懒加载
    if (viewPath) {
      return () => import(`src/pages/${viewPath}`);
    } else {
      return null;
    }
  }

  //生成菜单树并存储
  const generateMenuTree = (list: menuItem[]): CMenu[] => {
    let menuList: CMenu[] = [];

    //递归函数
    const filterTree = (ls: menuItem[], arr: CMenu[]) => {
      ls.forEach((item: menuItem) => {
        let el = [] as CMenu[];
        if (item.children && item.children.length > 0) {
          filterTree(item.children, el);
        }

        //路由节点
        arr.push({
          id: item.id,
          name: item.value,
          path: item.url,
          meta: {
            icon: item.icon,
            title: item.label
          },
          component: loadView(item.component),
          children: el
        });
      });
    };

    //调用递归函数
    filterTree(list, menuList);

    //console.log(menuList);
    return menuList;
  }

  //路由封装
  const routerPackage = (router: Router, menuList: CMenu[]) => {
    menuList?.forEach((item: CMenu) => {
      item.children?.forEach((el) => {
        if (!router.hasRoute(el.name)) {
          router.addRoute('Layout', {
            name: el.name,
            path: el.path,
            meta: {
              icon: el.meta.icon,
              title: el.meta.title
            },
            component: el.component,
            children: el.children
          });
        }
      })
    });

    //动态404
    router.addRoute({
      name: 'Error',
      path: '/:catchAll(.*)*',
      redirect: '/404'
    });
  }

  return {
    generateMenuTree,
    routerPackage
  }
}
